<template>
  <CDialog
    title="年度履约清缴"
    :close-on-click-modal="false"
    v-model:visible="dialogVisible"
    size="small"
    @cancel="handleClose"
    @confirm="handleConfirm"
    cancel-text="取消"
    confirm-text="履约清缴"
    :footerDescText="`履约清缴合计：${selectedAllowance} tCO₂`"
  >
    <div class="compliance-asset-dialog-container" v-loading="loading">
      <div class="asset-info">
        <div class="asset-info__company">{{ empty(props.tempRow?.dischargeUnit) }}</div>
        <div class="asset-info__details g-mt10 g-mb14 g-pb13">
          <div class="info-details__item g-flex-start-center">
            <div class="label">履约年份：</div>
            <div class="value">{{ empty(props.tempRow?.dischargeYear) }}</div>
          </div>
          <div class="info-details__item g-flex-start-center">
            <div class="label">年度核查量：</div>
            <div class="value">{{ empty(props.tempRow?.carbonInspectEmission) }} tCO₂</div>
          </div>
          <div class="info-details__item g-flex-start-center">
            <div class="label">应清缴量：</div>
            <div class="value">{{ empty(props.tempRow?.carbonInspectEmission) }} tCO₂</div>
          </div>
        </div>
      </div>
      <div class="asset-select">
        <div class="asset-select__title g-mb11">
          <div class="select-title__text g-font-14n1b500">选择碳资产履约清缴</div>
          <div class="select-title__tips g-flex-start-center">
            <CIcon type="c-mian-tishi" class="g-mr4 title-tips__icon" />
            使用减排量(CCER、CQCER)的占比不得超过清缴量的8%
          </div>
        </div>
        <div class="pay-select__container">
          <el-form ref="formRef" :model="formData" label-position="top" hide-required-asterisk>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item
                  v-for="item in allowanceList"
                  :key="item.assetTypeCode"
                  :prop="item.assetTypeCode"
                  :rules="itemRules(item.assetTypeCode)"
                >
                  <template #label>
                    <div class="g-flex-between-center">
                      <span class="item-label__text">{{ item.assetTypeName }}:</span>
                      <span class="item-label__tips"
                        >可用量：{{ empty(item.availableQuota) }} tCO₂</span
                      >
                    </div>
                  </template>
                  <el-input
                    v-model="formData[item.assetTypeCode]"
                    type="number"
                    placeholder="请输入"
                    clearable
                  >
                    <template #suffix>tCO₂</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </div>
  </CDialog>
</template>
<script lang="ts" setup name="ComplianceDialog">
import { defineProps, withDefaults, defineEmits, computed, ref, watch, reactive } from 'vue';
import { CDialog } from '@/components/CDialog';
import { useMessage } from '@/hooks/useMessage';
import { getFindCarbonAllowance, postCarbonEmissionInspect } from '@/apis/taa/asset/inspect';
import type {
  GetInspectListResult,
  GetFindCarbonAllowanceResult,
  PostCarbonEmissionInspectParams
} from '@/apis/taa/asset/model/inspectModel';
import { empty } from '@/utils';
import Decimal from 'decimal.js';

interface ComplianceDialogProps {
  visible: boolean;
  loading?: boolean;
  tempRow?: GetInspectListResult;
}
const props = withDefaults(defineProps<ComplianceDialogProps>(), {});
const emits = defineEmits(['update:visible', 'refresh']);
const { createMessage } = useMessage();
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emits('update:visible', val);
  }
});

watch(
  () => props.visible,
  val => {
    if (val) {
      init();
    }
  }
);

const formRef = ref();
const loading = ref(false);
let formData = reactive<Record<string, string>>({});
const allowanceList = ref<GetFindCarbonAllowanceResult[]>([]);
const selectedAllowance = computed(() => {
  let sum = 0;
  for (let i = 0; i < allowanceList.value.length; i++) {
    const item = allowanceList.value[i];
    sum = Decimal.add(sum, formData[item.assetTypeCode] || 0).toNumber();
  }
  return sum;
});

/**
 * 规则
 * @param assetTypeCode
 */
const itemRules = (assetTypeCode: string) => {
  return [
    {
      // eslint-disable-next-line no-undef
      validator: (_: any, value: number, callback: Fn) =>
        allowanceValidator(assetTypeCode, value, callback),
      trigger: ['submit', 'blur', 'change'],
      transform: (val: string) => {
        return Number(val);
      }
    }
  ];
};
// eslint-disable-next-line no-undef
function allowanceValidator(assetTypeCode: string, value: number, callback: Fn) {
  const item = allowanceList.value?.find(item => item.assetTypeCode === assetTypeCode);
  console.log('allowanceValidator', item);
  if (item && value > item.availableQuota) {
    return callback('超出可用量');
  }
  callback();
}

/**
 * 初始化
 */
async function init() {
  // 初始化
  formData = reactive<Record<string, string>>({});
  if (props.tempRow) {
    const params = {
      organizationCode: props.tempRow.organizationCode,
      dischargeYear: props.tempRow.dischargeYear
    };
    try {
      const res = await getFindCarbonAllowance(params);
      allowanceList.value = res || [];
      allowanceList.value.forEach(item => {
        formData[item.assetTypeCode] = '';
      });
    } catch (error) {
      console.log('error', error);
      allowanceList.value = [];
    }
  }
}

/**
 * 提交履约
 */
function handleConfirm() {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (!props.tempRow) {
        createMessage.error('异常错误，请刷新重试！');
        return;
      }
      if (props.tempRow.carbonInspectEmission !== selectedAllowance.value) {
        createMessage.error('已选清缴量不等于应清缴量，请检查！');
        return;
      }
      try {
        loading.value = true;
        const performanceDataList: PostCarbonEmissionInspectParams['performanceDataList'] =
          allowanceList.value?.map(item => {
            return {
              assetTypeCode: item.assetTypeCode,
              availableQuota: Number(formData[item.assetTypeCode]) || 0
            };
          }) || [];
        const params = {
          inspectNo: props.tempRow.inspectNo,
          performanceDataList
        };
        await postCarbonEmissionInspect(params);
        createMessage.success('履约成功！');
        loading.value = false;
        emits('refresh');
        handleClose();
      } catch (error) {
        loading.value = false;
        console.log('error', error);
      }
    }
  });
}

function handleClose() {
  dialogVisible.value = false;
}
</script>

<style lang="scss" scoped>
.compliance-asset-dialog-container {
  .asset-info {
    .asset-info__company {
      font-family: PingFangSC, PingFang SC;
      font-weight: 600;
      font-size: 14px;
      color: #0a1f33;
      line-height: 22px;
      text-align: left;
      font-style: normal;
    }
    .asset-info__details {
      border-bottom: 1px solid #f2f3f5;
      .info-details__item {
        height: 34px;
        .label {
          width: 90px;
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 14px;
          color: #0a1f33;
          line-height: 22px;
          text-align: left;
          font-style: normal;
        }
        .value {
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 14px;
          color: #435970;
          line-height: 22px;
          text-align: left;
          font-style: normal;
        }
      }
    }
  }
  .asset-select {
    .asset-select__title {
      .select-title__text {
        font-family: PingFangSC, PingFang SC;
        text-align: left;
        font-style: normal;
      }
      .select-title__tips {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 12px;
        color: #7a8a99;
        line-height: 20px;
        text-align: left;
        font-style: normal;
        .title-tips__icon {
          color: #5a739a;
        }
      }
    }
    .pay-select__container {
      padding: 12px 16px 0;
      width: 420px;
      // height: 244px;
      background: #f3f7fb;
      border-radius: 3px;
      border: 1px solid #f2f3f5;
      .item-label__text {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 14px;
        color: #0a1f33;
        line-height: 22px;
        text-align: left;
        font-style: normal;
      }
      .item-label__tips {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 12px;
        color: #7a8a99;
        line-height: 20px;
        text-align: right;
        font-style: normal;
      }
    }
  }
}
</style>
